package com.ysq;

import java.util.*;
import java.util.function.Consumer;

public class StudentManager {
    private static final Scanner scanner = new Scanner(System.in);
    private static final Map<Integer, Consumer<List<Student2>>> Manager = new HashMap<>();
    static {
        Manager.put(1, StudentManager::addStudent);
        Manager.put(2, StudentManager::deleteStudent);
        Manager.put(3, StudentManager::updateStudent);
        Manager.put(4, StudentManager::queryStudents);
        Manager.put(5, students -> System.out.println("感谢您的使用，再见！"));
    }

    public static void main(String[] args) {
        List<Student2> students = new ArrayList<>();
        students.add(new Student2("蔡徐坤", 27, "001", "浙江"));
        students.add(new Student2("陈立农", 25, "002", "台湾"));
        students.add(new Student2("范丞丞", 25, "003", "山东"));
        students.add(new Student2("黄明昊", 23, "004", "浙江"));
        students.add(new Student2("林彦俊", 29, "005", "北京"));
        students.add(new Student2("朱正廷", 28, "006", "北京"));
        students.add(new Student2("王子异", 30, "007", "上海"));
        students.add(new Student2("王琳凯", 25, "008", "北京"));
        students.add(new Student2("尤长靖", 30, "009", "湖南"));
        while (true) {
            printMenu();
            int choice = getValidChoice(1, 5);
            if (choice == 5) {
                Manager.get(5).accept(students);
                break;
            }
            Manager.getOrDefault(choice,
                            s -> System.out.println("输入有误，请重新选择！"))
                    .accept(students);
        }

        scanner.close();
    }

    private static void printMenu() {
        System.out.println("-----欢迎使用学生管理系统-----");
        System.out.println("1. 添加学生");
        System.out.println("2. 删除学生");
        System.out.println("3. 修改学生");
        System.out.println("4. 查询学生");
        System.out.println("5. 退出系统");
        System.out.print("请输入您的选择：");
    }

    private static int getValidChoice(int min, int max) {
        while (true) {
            try {
                int choice = scanner.nextInt();
                scanner.nextLine();
                if (choice >= min && choice <= max) {
                    return choice;
                } else {
                    System.out.printf("请输入 %d-%d 之间的数字：", min, max);
                }
            } catch (Exception e) {
                System.out.printf("请输入 %d-%d 之间的数字：", min, max);
                scanner.nextLine();
            }
        }
    }

    private static void addStudent(List<Student2> students) {
        System.out.println("-----添加学生-----");
        String sid = getInput("请输入学生学号：");

        if (getIndex(students, sid) != -1) {
            System.out.println("该学号已存在！");
            return;
        }

        String name = getInput("请输入学生姓名：");
        int age = getValidNumber(0, 150);
        String address = getInput("请输入学生居住地：");


        Student2 student = new Student2(name, age, sid,address);
        student.setAddress(address);
        students.add(student);
        System.out.println("添加学生成功！");
    }
         //  删除学生
    private static void deleteStudent(List<Student2> students) {
        System.out.println("-----删除学生-----");

        // 先判断列表是否为空
        if (students.isEmpty()) {
            System.out.println("学生列表为空，无法删除！");
            return;
        }

        String sid = getInput("请输入要删除的学生学号：");
        int index = getIndex(students, sid);

        if (index == -1) {
            System.out.println("该学生不存在！");
        } else {
            students.remove(index);
            System.out.println("删除学生成功！");
        }
    }
     //修改学生列表
     private static void updateStudent(List<Student2> students) {
         System.out.println("-----修改学生-----");
         // 先判断学生列表是否为空
         if (students.isEmpty()) {
             System.out.println("学生列表为空，无法修改！");
             return;
         }
         String sid = getInput("请输入要修改的学生学号：");
         int index = getIndex(students, sid);

         if (index == -1) {
             System.out.println("该学生不存在！");
             return;
         }
         Student2 student2 = students.get(index);
         System.out.printf("当前信息：%s%n", formatStudent(student2));
         // 修改学号（增加唯一性检查）
         String newSid = getInput("请输入新学号：", student2.getStudentId());
         if (!newSid.equals(student2.getStudentId()) && getIndex(students, newSid) != -1) {
             System.out.println("该学号已存在！");
             return;
         }
         student2.setStudentId(newSid);
         student2.setName(getInput("请输入新姓名：", student2.getName()));
         student2.setAge(getValidNumber(student2.getAge()));
         student2.setAddress(getInput("请输入新居住地：", student2.getAddress()));

         System.out.println("修改学生成功！");
     }


        //查询学生列表
        private static void queryStudents(List<Student2> students) {
            System.out.println("-----查询学生-----");
            if (students.isEmpty()) {
                System.out.println("暂无学生信息！");
                return;
            }

            // 新增：按学号升序排序（字符串字典序）
            List<Student2> sortedStudents = new ArrayList<>(students);
            sortedStudents.sort(Comparator.comparing(Student2::getStudentId)); // 按学号排序
            System.out.println("学号 \t姓名 \t年龄 \t居住地");
            sortedStudents.forEach(student -> System.out.println(formatStudent(student)));
        }


       //获取输出
    private static int getIndex(List<Student2> students, String sid) {
        for (int i = 0; i < students.size(); i++) {
            if (students.get(i).getStudentId().equals(sid)) {
                return i;
            }
        }
        return -1;
    }

    private static String formatStudent(Student2 student) {
        return String.format("%s\t%s\t%d岁\t%s",
                student.getStudentId(),
                student.getName(),
                student.getAge(),
                student.getAddress());
    }

    private static String getInput(String prompt) {
        System.out.print(prompt);
        return scanner.nextLine();
    }

    private static String getInput(String prompt, String defaultValue) {
        System.out.print(prompt);
        String input = scanner.nextLine();
        return input.isEmpty() ? defaultValue : input;
    }

    private static int getValidNumber(int min, int max) {
        while (true) {
            String input = getInput("请输入学生年龄：");
            try {
                int value = Integer.parseInt(input);
                if (value >= min && value <= max) {
                    return value;
                } else {
                    System.out.printf("请输入 %d-%d 之间的数字！%n", min, max);
                }
            } catch (NumberFormatException e) {
                System.out.println("请输入有效的数字！");
            }
        }
    }

    private static int getValidNumber(int defaultValue) {
        String input = getInput("请输入新年龄：");
        if (input.isEmpty()) {
            return defaultValue;
        }
        try {
            int value = Integer.parseInt(input);
            if (value >= 0 && value <= 150) {
                return value;
            } else {
                System.out.printf("请输入 %d-%d 之间的数字！%n", 0, 150);
                return defaultValue;
            }
        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字！");
            return defaultValue;
        }
    }
}